package com.itzxx.huazhun.data.dao

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.itzxx.library_base_ktx.base.appContext

/**
 * Desc:
 *
 * Author: zhangxiaoxiao
 * Date: 2024/8/6 19:23
 * Updater:
 * Update Time:
 * Update Comments:
 */
class DbHelper constructor(context: Context) {

    private var appDb: AppDataBase? = null
    private val DB_NAME = "room_huazhun_db.db"

    /**
     * 初始化 db
     */
    init {
        appDb = Room.databaseBuilder(context,
            AppDataBase::class.java,
            DB_NAME)
            .build()
        //.addMigrations(MigrateDb(1, 2))
    }

    fun getCollectionDao(): CollectionDao {
        return appDb!!.collectionDao()
    }

    fun getProbeRecordDao(): ProbeRecordDao {
        return appDb!!.probeRecordDao()
    }



    /**
     * 单例实现
     */
    companion object {

        var INSTANCE: DbHelper? = null

        fun init(): DbHelper {
            if (INSTANCE == null) {
                synchronized(DbHelper::class) {
                    if (INSTANCE == null) {
                        INSTANCE = DbHelper(appContext)
                    }
                }
            }
            return INSTANCE!!
        }

    }

    /**
     * 关闭数据库
     */
    fun onDestory() {
        if (appDb != null) {
            appDb!!.close()
        }
    }

    /**
     * 版本合并
     */
    class MigrateDb(startVersion: Int, endVersion: Int) : Migration(startVersion, endVersion) {

        override fun migrate(database: SupportSQLiteDatabase) {

        }
    }

}